package com.itqf.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/12/25
 * @Time: 上午10:35
 */
@Component
public class TokenFilter extends ZuulFilter {

    /**
     * 类型  pre(前)  post(后)  router(路由)  error(异常)
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
        //return "pre";
        }

    /**
     * 执行顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 3;
    }

    /**
     * 是否通过
     * @return
     */
    @Override
    public boolean shouldFilter() {
        boolean f = RequestContext.getCurrentContext().sendZuulResponse();
        System.out.println("f:"+f);//得到上一个过滤器返回的值

        //如果true:执行该过滤器   执行run
        //如果false:不执行该过滤器
        return f;
    }

    @Override
    public Object run() throws ZuulException {
        //权限校验  认证校验
        //1.请求上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        //2.获得请求参数
        String token = request.getParameter("token");
        //3.校验
        //  redis
        if (token==null||!"abc".equals(token)){
            //校验不通过  后续业务不能访问
            context.setSendZuulResponse(false);//注意顺序
            //校验不通过
            //  UNAUTHORIZED(401, "Unauthorized"),
            //响应的状态码
           // context.getResponse().setContentType("text/html;charset=utf-8");
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            //响应的文本
            //context.setResponseBody("你没有权限，请检查token是否正确");


        }

        return null;
    }
}
